from typing import Dict, Union

from client.redis_client import r
from service.battery import get_intensity_redis
from utils.date_utils import timestamp_to_str


def blood_pressure_valid(systolic: int, diastolic: int) -> Dict[str, Union[str, tuple]]:
    """
    优化后的血压分级监测函数（性能增强版）
    判断逻辑短路设计：符合条件立即返回，不再执行后续判断
    """
    # 有效性验证（防止无效值穿透）
    if not validate_range(systolic, diastolic):
        return None
    # 理想血压判断
    if optimal_check(systolic, diastolic):
        return None
    # 危急情况优先判断
    if is_hypertension_crisis(systolic, diastolic):
        return format_alert((systolic, diastolic),
                            "高血压危象", "严重预警：确认后立即送医急诊", warning_level=3)

    # 分级判断短路逻辑（按临床风险降序排列）
    return \
        stage2_check(systolic, diastolic) or \
        stage1_check(systolic, diastolic) or \
        isolated_systolic_check(systolic, diastolic) or \
        pre_hypertension_check(systolic, diastolic) or \
        high_normal_check(systolic, diastolic)


def validate_range(s: int, d: int) -> bool:
    """血压值物理范围验证"""
    return 50 <= s <= 250 and 30 <= d <= 150


def is_hypertension_crisis(s: int, d: int) -> bool:
    """高血压危象判断（收缩压>180 或 舒张压>120）"""
    return s > 180 or d > 120


def stage2_check(s: int, d: int) -> Union[dict, None]:
    """二级高血压判断"""
    if s >= 160 or d >= 100:
        return format_alert((s, d), "二级高血压",
                            "中度预警：立即就医，2小时内复测血压", warning_level=2)
    return None


def stage1_check(s: int, d: int) -> Union[dict, None]:
    """一级高血压判断"""
    if s >= 140 or d >= 95:
        return format_alert((s, d), "一级高血压",
                            "一般预警：3天内到心血管科就诊", warning_level=1)
    return None


def isolated_systolic_check(s: int, d: int) -> Union[dict, None]:
    """单纯收缩期高血压判断"""
    if s >= 140 and d < 90:
        return format_alert((s, d), "单纯收缩期高血压",
                            "建议进行24小时动态血压监测")
    return None


def pre_hypertension_check(s: int, d: int) -> Union[dict, None]:
    """高血压前期判断"""
    if 130 <= s <= 139 or 85 <= d <= 89:
        return format_alert((s, d), "高血压前期",
                            "每月监测血压，改善饮食结构")
    return None


def high_normal_check(s: int, d: int) -> Union[dict, None]:
    """正常高值判断"""
    if 120 < s < 130 or 80 < d < 85:
        return format_alert((s, d), "正常高值",
                            "每周监测血压变化趋势")
    return None


def optimal_check(s: int, d: int) -> Union[dict, None]:
    """理想血压判断"""
    if s <= 120 and d <= 80:
        return format_alert((s, d), "理想血压",
                            "保持当前健康生活方式")
    return None


def format_alert(values: tuple, blood_pressure_level: str, advice: str, warning_level: int = 0) -> dict:
    """统一格式化输出"""
    return {
        "value": f"{values[0]}/{values[1]} mmHg",
        "blood_pressure_level": blood_pressure_level,
        "advice": advice,
        "warning_level": warning_level
    }


def build_body_temperature_keyword(alert: str, value: float, depart_name: str, name: str, timestamp: float):
    return {
        'thing4': {
            "value": depart_name,
            "color": "#173177"
        },
        'thing5': {
            "value": name,
            "color": "#173177"
        },
        'time1': {
            "value": timestamp_to_str(timestamp),
            "color": "#173177"
        },
        'character_string2': {
            "value": value,
            "color": "#173177"
        },
        'const3': {
            "value": alert,
            "color": "#173177"
        }
    }


async def generate_heart_rate_wechat_template(heart_rate: int, device_id: str, name: str, timestamp: int, intensity:int) -> dict:
    """
    生成微信服务号模板消息data字典，包含心率异常检测信息。

    参数:
        heart_rate (int): 实测心率值
        device_id (str): 设备编号
        name (str): 人员姓名
        timestamp (int): 检测时间戳

    返回:
        dict: 微信模板消息data字典
    """
    # 时间处理（格式：YYYY-MM-DD HH:mm）
    formatted_time = timestamp_to_str(timestamp)
    # 异常类型判定逻辑（可配置阈值）
    if heart_rate < 50 or heart_rate >= 140:
        if intensity <= 1:
            abnormal_type = "重度异常"
    # elif 105 <= heart_rate <= 120:
    #     abnormal_type = "轻度异常"
    elif 121 <= heart_rate <= 140:
        if intensity <= 1:
            abnormal_type = "中度异常"
    else:
        return None

    # 构建模板数据字典
    return {
        "thing3": {"value": name},  # 人员姓名
        "character_string5": {"value": str(heart_rate)},  # 心率值
        "const2": {"value": abnormal_type},  # 异常类型
        "time4": {"value": formatted_time},  # 检测时间
        "character_string8": {"value": device_id}  # 设备编号
    }


def temperature_valid(temp_c: float) -> str:
    if 35.5 <= temp_c < 37.3:
        return None
    elif temp_c < 32.0:
        return "低温2级：请及时联系确认情况并就医"
    elif 32.0 <= temp_c < 35.5:
        return "低温1级：建议增加保暖措施"
    elif 37.3 <= temp_c < 38.0:
        return "高温1级：建议确认情况休息"
    elif 38.0 <= temp_c < 39.0:
        return "高温2级：请及时联系确认进行降温救护"
    else:
        return "高温3级：请及时联系确认就医"


def build_sos_keyword(content: str, timestamp:int):
    data = {
        'first': {
            "value": 'SOS预警',
            "color": "#173177"
        },
        'keyword1': {
            "value": content,
            "color": "#173177"
        },
        'keyword2': {
            "value": timestamp_to_str(timestamp),
            "color": "#173177"
        },
        'remark': {
            "value": '请及时确认人员安全情况',
            "color": "#173177"
        }
    }
    return data
